<template>
  <div class="addExpense app-container">
    <el-form ref="form" :model="form" :rules="roleCodeRule" label-width="120px">
      <el-row>
        <mainTilte title="基本信息" />
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="商品分类" prop="category_id">
            <!-- !!form.category_id || -->
            <product-category v-model="form.category_id" :disabled="disabled" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配件编码" prop="code">
            <el-input v-model.trim="form.code" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配件名称" prop="name_ch">
            <el-input v-model.trim="form.name_ch" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配件流向" prop="flow_to">
            <el-select v-model.trim="form.flow_to" clearable placeholder="配件流向">
              <el-option v-for="(item, index) of flwList" :key="index" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属供应商" prop="supplier_id">
            <app-select v-model="form.supplier_id" url="/supply" :params="supplyParams" options-label="name" options-value="id" placeholder="请输入内容" @change="changeSupplyHandler" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购员" prop="purchase_id">
            <app-select v-model="form.purchase_id" url="/shops/buyers" :params="purchaseParams" options-label="username" options-value="user_id" placeholder="请输入内容" @change="changePurchaseHandler" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配件主图" prop="image_url">
            <upload-file accept-type="image/jpeg,image/png" list-type="picture-card" :file-list="imageList" :upload-limit="1" @handleImageSuccess="handleImageSuccess" @beforeRemoveFile="beforeImageUpload" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <mainTilte title="包装信息" />
      </el-row>
      <div class="filter-selection">
        <el-form-item label="邮购包装尺寸" :label-width="labelWidth">
          <div class="sizeStyle">
            <div>
              <el-form-item label="" prop="length">
                <el-input v-model="form.length" class="minwidth100" placeholder="长" @input="sizeChange($event, 'length_AS')">
                  <template slot="append">CM</template>
                </el-input>
              </el-form-item>
            </div>
            <div style="margin-left: 8px">
              <el-form-item label="" prop="width">
                <el-input v-model="form.width" class="minwidth100" placeholder="宽" @input="sizeChange($event, 'width_AS')">
                  <template slot="append">CM</template>
                </el-input>
              </el-form-item>
            </div>
            <div style="margin-left: 8px">
              <el-form-item label="" prop="height">
                <el-input v-model="form.height" class="minwidth100" placeholder="高" @input="sizeChange($event, 'height_AS')">
                  <template slot="append">CM</template>
                </el-input>
              </el-form-item>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="体积(公制)" :label-width="labelWidth">
          <el-input v-model.trim="volume" disabled />
        </el-form-item>
        <el-form-item label="邮购包装尺寸(美制)" :label-width="labelWidth">
          <div class="sizeStyle">
            <div>
              <el-form-item label="" prop="length">
                <el-input v-model="form.length_AS" class="minwidth100" placeholder="长" disabled>
                  <template slot="append">英寸</template>
                </el-input>
              </el-form-item>
            </div>
            <div style="margin-left: 8px">
              <el-form-item label="" prop="width">
                <el-input v-model="form.width_AS" class="minwidth100" placeholder="宽" disabled>
                  <template slot="append">英寸</template>
                </el-input>
              </el-form-item>
            </div>
            <div style="margin-left: 8px">
              <el-form-item label="" prop="height">
                <el-input v-model="form.height_AS" class="minwidth100" placeholder="高" disabled>
                  <template slot="append">英寸</template>
                </el-input>
              </el-form-item>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="毛重（美制）" prop="weight_gross_AS" :label-width="labelWidth">
          <el-input v-model="form.weight_gross_AS" placeholder="请输入内容">
            <template slot="append">lbs</template>
          </el-input>
        </el-form-item>
        <!-- </el-col> -->
        <!-- <el-col :span="8">
          <el-form-item label="外箱包装尺寸">
            <div class="sizeStyle">
              <div>
                <el-form-item label="" prop="length_outside">
                  <el-input v-model="form.length_outside" placeholder="长">
                    <template slot="append">CM</template>
                  </el-input>
                </el-form-item>
              </div>
              <div style="margin-left: 8px">
                <el-form-item label="" prop="width_outside">
                  <el-input v-model="form.width_outside" placeholder="宽">
                    <template slot="append">CM</template>
                  </el-input>
                </el-form-item>
              </div>
              <div style="margin-left: 8px">
                <el-form-item label="" prop="height_outside">
                  <el-input v-model="form.height_outside" placeholder="高">
                    <template slot="append">CM</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
          </el-form-item>
        </!-->
        <el-form-item label="体积" :label-width="labelWidth">
          <el-input v-model.trim="volume_outside" disabled />
        </el-form-item>
        <el-form-item label="外箱箱率" prop="box_rate" :label-width="labelWidth">
          <el-input v-model.trim="form.box_rate" />
        </el-form-item>
      </div>
      <el-row>
        <mainTilte title="适用SKU" class="mb0" />
      </el-row>
      <div class="operation_button_box">
        <el-button type="primary" @click="selectProduct">选择商品</el-button>
      </div>
      <el-row>
        <egrid v-loading="loading" class="egrid" stripe fit border highlight-current-row element-loading-text="正在努力加载中..." :data="tableData" :columns="columns" :columns-schema="columnsSchema" :columns-handler="columnsHandler" @selection-change="checkIds" />
      </el-row>
      <div class="dialog-footer-center">
        <span>
          <el-button type="primary" :loading="btnLoading" @click="onSubmit">保存</el-button>
          <el-button @click="$router.push('/product/accessoriesManage')">取消</el-button>
        </span>
      </div>
    </el-form>
    <!-- 添加商品 -->
    <el-dialog v-if="dialogAddProductVisible" v-loading.lock="loading" v-loading="loading" title="" :visible.sync="dialogAddProductVisible" :close-on-click-modal="false" width="90%" class="dialogText header-none" element-loading-text="正在加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" center>
      <addProduct :addGlProduct="true" @checkChildIds="checkChildIds" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddProductVisible = false">取消选择</el-button>
        <el-button type="primary" @click="saveData()">确认选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import list from '@/layout/mixin/list'
import btnGroup from './components/btnGroup'
import thund from '@/components/base/thund'
import dicValues from '@/components/dicTransform/index'
import addProduct from '@/views/supplyChain/purchaseRequisition/components/addProduct'
import { isNumberThanZero } from '@/utils/validate'
export default {
  components: { addProduct },
  mixins: [list],
  data() {
    // 包装方式 ：1-普通商品 2-多箱包装
    const packMethodList = [
      {
        code: 1,
        name: '普通商品'
      },
      {
        code: 2,
        name: '多箱包装'
      }
    ]
    return {
      disabled: false,
      labelWidth: '150px',
      loading: false,
      productConfig: {}, // 商品配置
      form: {
        category_id: '', // 分类
        code: '', // 编码
        name_ch: '', // 配件名称
        flow_to: '', // 配件流向
        supplier_name: '', // 所属供应商
        supplier_id: '', // 所属供应商
        purchase_name: '', // 所属采购员
        purchase_id: '', // 所属采购员
        image_url: '', // 配件主图

        length: '',
        width: '',
        height: '',

        length_AS: '',
        width_AS: '',
        height_AS: '',
        volume: '',
        volume_AS: '',
        weight: '',
        length_outside: '',
        width_outside: '',
        height_outside: '',
        volume_outside: '',
        box_rate: '',

        product_id: ''
      },
      roleCodeRule: {
        // 商品分类
        category_id: [
          {
            required: true,
            message: '请选择配件分类',
            trigger: ['change', 'blur']
          }
        ],
        // 配件名称
        name_ch: [
          { required: true, message: '请输入配件名称', trigger: 'blur' },
          { max: 30, message: '配件名称必须在30个字符以内', trigger: 'blur' }
        ],
        // 配件流向
        flow_to: [
          {
            required: true,
            message: '请选择配件流向',
            trigger: ['change', 'blur']
          }
        ],
        // 所属供应商
        supplier_id: [
          {
            required: true,
            message: '请选择所属供应商',
            trigger: ['change', 'blur']
          }
        ],
        // 采购员
        purchase_id: [
          {
            required: true,
            message: '请选择采购员',
            trigger: ['change', 'blur']
          }
        ],
        // 配件主图
        image_url: [
          {
            required: true,
            message: '请选择上传配件主图',
            trigger: ['change', 'blur']
          }
        ],
        // 长度
        length: [
          { required: true, message: '请输入长', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              isNumberThanZero(value)
                ? callback()
                : callback(new Error('必须是数字且大于0'))
            },
            trigger: 'blur'
          }
        ],
        // 宽度
        width: [
          { required: true, message: '请输入宽', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              isNumberThanZero(value)
                ? callback()
                : callback(new Error('必须是数字且大于0'))
            },
            trigger: 'blur'
          }
        ],
        // 高度
        height: [
          { required: true, message: '请输入高', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              isNumberThanZero(value)
                ? callback()
                : callback(new Error('必须是数字且大于0'))
            },
            trigger: 'blur'
          }
        ],
        // 体重
        weight_gross_AS: [
          { required: true, message: '请输入毛重（美制）', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              isNumberThanZero(value)
                ? callback()
                : callback(new Error('必须是数字且大于0'))
            },
            trigger: 'blur'
          }
        ],
        // 长度
        length_outside: [
          { required: true, message: '请输入长', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              isNumberThanZero(value)
                ? callback()
                : callback(new Error('必须是数字且大于0'))
            },
            trigger: 'blur'
          }
        ],
        // 宽度
        width_outside: [
          { required: true, message: '请输入宽', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              isNumberThanZero(value)
                ? callback()
                : callback(new Error('必须是数字且大于0'))
            },
            trigger: 'blur'
          }
        ],
        // 高度
        height_outside: [
          { required: true, message: '请输入高', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              isNumberThanZero(value)
                ? callback()
                : callback(new Error('必须是数字且大于0'))
            },
            trigger: 'blur'
          }
        ]
      },
      freightList: [],
      columns: [
        {
          label: '缩略图',
          prop: 'image_url',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '系统sku',
          prop: 'code',
          align: 'center',
          tooltip: false
        },
        {
          label: '中文名称',
          prop: 'name_ch',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '英文名称',
          prop: 'name_en',
          align: 'center',
          tooltip: false
        },
        {
          label: '包装方式',
          prop: 'packing_method',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '商品分类',
          prop: 'category_text',
          width: '200',
          align: 'center',
          tooltip: false
        }
      ],
      columnsSchema: {
        缩略图: {
          propsHandler({ col, row }) {
            return {
              img: row.image_url
            }
          },
          component: thund
        },
        包装方式: {
          propsHandler({ col, row }) {
            return {
              dictionaries: packMethodList,
              code: row[col.prop]
            }
          },
          component: dicValues
        }
      },
      fileList: [],
      dialogAddProductVisible: false,
      checkChildList: [],
      classifyList: [],
      propsClassify: {
        disabled: 'disabled' // 商品分类只能选择二级
      },
      // 配件流向 流向 1-国内 2-国外
      flwList: [
        {
          name: '国内',
          code: 1
        },
        {
          name: '国外',
          code: 2
        }
      ],
      imageAction: process.env.VUE_APP_BASE_API + '/upload/image',
      headers: {
        authorization: ''
      },
      tableData: [],
      isEdit: false,
      btnLoading: false,
      supplyParams: {
        page: 1,
        limit: 100000000,
        audit_status: 2,
        cooperation_status: 1
      },
      purchaseParams: {
        status: 1
      },
      imageList: []
    }
  },
  computed: {
    ...mapGetters(['name', 'avatar', 'roles', 'email', 'token', 'user_id']),
    volume() {
      const vm = this
      const { length, width, height } = this.form
      return vm.getVolume(length, width, height)
    },
    volume_AS() {
      const vm = this
      const { length_AS, width_AS, height_AS } = this.form
      return vm.getVolume(length_AS, width_AS, height_AS, false)
    },
    volume_outside() {
      const vm = this
      const { length_outside, width_outside, height_outside } = this.form
      return vm.getVolume(length_outside, width_outside, height_outside)
    },
    // 厘米  转为 英寸的 config
    lengthConfig({ productConfig }) {
      return productConfig ? productConfig.cm_to_in : 0
    },
    // kg 转为 磅
    weightConfig({ productConfig }) {
      return productConfig ? productConfig.kg_to_pt : 0
    }
  },
  mounted() {
    this.getTreeList()
    this.editList()
    this.getProductConfig() // 获取商品配置信息
  },
  methods: {
    // 获取商品配置信息
    getProductConfig() {
      const vm = this
      vm.$http.get(`/config/product`).then(res => {
        vm.productConfig = res.data.product
      })
    },
    // 获取体积
    getVolume(length, width, height, isParse = true) {
      const vm = this
      // length, width, height 单位 为 cm 需要转为 m
      if (isParse) {
        length = length / 100
        width = width / 100
        height = height / 100
      }
      return +vm.$computed.accMul(length, vm.$computed.accMul(width, height)).toFixed(6)
    },
    editList() {
      if (this.$route.query && this.$route.query.id) {
        this.isEdit = true
        this.getDatailData(this.$route.query.id)
      }
    },
    getDatailData(id) {
      this.$http
        .get(`/parts/${id}`)
        .then((res) => {
          if (res.code === 10000) {
            this.form = res.data
            this.imageList = [{ url: res.data.image_url }]
            if (res.data.list && res.data.list.length > 0) {
              this.tableData = res.data.list
            }
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 获取商品分类
    getTreeList() {
      this.$http
        .get(`/getListTree`)
        .then((res) => {
          if (res.code === 10000 && res.data && res.data.length > 0) {
            res.data.forEach((element) => {
              element['label'] = element.name
              element['value'] = element.id
              if (element.children && element.children.length > 0) {
                element['disabled'] = false
                element.children.forEach((it) => {
                  it['label'] = it.name
                  it['value'] = it.id
                })
              } else {
                element['disabled'] = true
              }
            })
            this.classifyList = res.data
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handleChangeClassify(data) {
      this.form.category_id = data[1]
      this.classifyList.forEach((element) => {
        if (element.children && element.children.length > 0) {
          element.children.forEach((it) => {
            if (it.id === this.form.category_id) {
              this.form.ZH_HS = it.ZH_HS
              this.form.EN_HS = it.EN_HS
              this.form.tax_rebate_rate = it.tax_rebate_rate
              this.form.tax_tariff_rate = it.tax_tariff_rate
            }
          })
        }
      })
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        )
      }
    },
    changePurchaseHandler(e) {
      this.form.purchase_name = e.label
    },
    changeSupplyHandler(e) {
      this.form.supplier_name = e.label
    },
    handleSelect() { },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '200',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({ row }) {
          return { row: row }
        },
        component: btnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          deleteTableClick(row) {
            console.log(row, 'row>>>>')
            that.tableData = that.tableData.filter((item) => {
              return row.id !== item.id
            })
          }
        }
      })
    },
    handleImageSuccess({ name, url }) {
      this.form.image_url = url
      this.imageList.push({ name, url })
    },
    beforeImageUpload(file) {
      this.imageList = []
    },
    beforeRemoveFile() {
      this.fileList = []
    },
    // 选择商品
    selectProduct() {
      this.dialogAddProductVisible = true
    },
    saveData() {
      const dataLength = this.checkChildList.length
      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }
      // 审核状态 0-待提交 1-待采购员审核 2-待运营审核 3-运营审核通过     -1 采购员审核驳回 -2 运营员审核驳回
      const midlle = this.checkChildList.findIndex((item) => {
        return (
          item['status'] === 0 || item['status'] === -1 || item['status'] === -2
        )
      })
      if (midlle !== -1) {
        this.$message.error('请选择提交审核的商品')
        return false
      }
      this.checkChildList.forEach((ele) => {
        const index = this.tableData.findIndex((e) => e.id === ele.id)
        if (index > -1) {
          this.tableData.splice(index, 1)
        }
        const productObj = {
          image_url: ele.image_url,
          code: ele.code,
          name_ch: ele.name_ch,
          name_en: ele.name_en,
          type: ele.type,
          category_name: ele.category_name,
          category_text: ele.category_text,
          packing_method: ele.packing_method,
          id: ele.id
        }
        this.tableData.push(productObj)
      })
      this.dialogAddProductVisible = false
    },
    checkChildIds(data) {
      this.checkChildList = data
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.tableData.length <= 0) {
            return this.$message.error('请至少选择添加一个商品')
          }
          this.btnLoading = true
          this.submit()
        }
      })
    },

    // 修改size 处理函数
    sizeChange(val, prop) {
      const vm = this
      vm.form[prop] = +(val * vm.lengthConfig).toFixed(6)
    },
    // 保存
    submit() {
      // this.form.product_id =
      //   this.ids && this.ids.length > 0 ? this.ids.join(',') : this.ids
      const vm = this
      vm.form.product_id = vm.tableData.map((e) => e.id).join(',')
      vm.form.volume = vm.volume
      vm.form.volume_AS = vm.volume_AS
      vm.form.volume_outside = vm.volume_outside
      const { length, width, height } = vm.form
      let params = Object.assign({}, vm.form)
      const lengthConfig = vm.lengthConfig
      const length_AS = +vm.$computed.accMul(length, lengthConfig).toFixed(6)
      const width_AS = +vm.$computed.accMul(width, lengthConfig).toFixed(6)
      const height_AS = +vm.$computed.accMul(height, lengthConfig).toFixed(6)
      params['length_AS'] = length_AS
      params['width_AS'] = width_AS
      params['height_AS'] = height_AS
      params['weight'] = 0
      params = this.coverNumberToString(params)
      if (vm.isEdit) {
        delete params.created_at
        delete params.updated_at
        // 编辑
        vm.$http
          .put(`/parts/${vm.form.id}`, params)
          .then((res) => {
            if (res.code === 10000) {
              vm.$message.success('修改成功')
              vm.$router.push('/product/accessoriesManage')
            }
            vm.btnLoading = false
          })
          .catch((err) => {
            console.log(err)
            vm.btnLoading = false
          })
      } else {
        vm.$http
          .post(`/parts`, params)
          .then((res) => {
            if (res.code === 10000) {
              vm.$message.success('新增成功')
              vm.$router.push('/product/accessoriesManage')
            }
            vm.btnLoading = false
          })
          .catch((err) => {
            console.log(err)
            vm.btnLoading = false
          })
      }
    },
    coverNumberToString(object) {
      for (const key in object) {
        if (Object.hasOwnProperty.call(object, key)) {
          const value = object[key]
          if (typeof value === 'number') {
            object[key] = value.toString()
          } else if (object[key].toString() === '[object Object]') {
            this.coverNumberToString(object[key])
          }
        }
      }
      return object
    }
  }
}
</script>

<style scoped>
.addExpense {
  padding: 15px;
  background: #fff;
}
.addExpense /deep/.el-select,
.el-autocomplete,
.el-cascader {
  width: 100%;
}
.sizeStyle {
  display: flex;
}
.sizeStyle /deep/ .el-input__inner {
  border-right: 0;
}
.sizeStyle /deep/ .el-input-group__append {
  padding-left: 4px;
  padding-right: 4px;
  font-size: 14px;
  color: #333333;
  background: #fff;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader /deep/ .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
